/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.jit.core.util;

import com.inspur.edp.jit.core.common.DirectoryManager;
import com.inspur.edp.jit.core.compile.BytesJavaFileObject;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;

/**
 * @author Kaixuan Shi
 * @since 2023/8/24
 */
public class JarUtil {

    //JAR文件后缀，避免采用.jar被轻易识别
    private final static String JAR_FILE_EXTENSION = ".jit";
    //JAR文件中目录分隔符，正斜杠（/），不区分操作系统
    private final static char JAR_FILE_SEPARATOR = '/';
    private final static String CLASS_FILE_EXTENSION = ".class";

    private final static Logger logger = LoggerFactory.getLogger(JarUtil.class);

    /**
     * 保存class字节码至目录的jar类型文件中
     *
     * @param dir             文件目录
     * @param fileName        文件名，不带后缀
     * @param compiledClasses 编译后的class字节码
     */
    public static void write(String dir, String fileName, List<BytesJavaFileObject> compiledClasses) {
        String jarFileName = getJARFileName(dir, fileName);
        try (JarOutputStream jarOutputStream = new JarOutputStream(Files.newOutputStream(Paths.get(jarFileName)))) {
            for (BytesJavaFileObject javaFileObject : compiledClasses) {
                // 写入类的字节码到JAR文件
                jarOutputStream.putNextEntry(new JarEntry(getJARFileEntryName(javaFileObject.getClassName())));
                jarOutputStream.write(javaFileObject.getClassBytes());
                jarOutputStream.closeEntry();
            }
        } catch (IOException e) {
            throw new JitIOException(e.getMessage(), e);
        }
    }

    /**
     * 从JAR中读取类字节码
     *
     * @param dir      文件目录
     * @param fileName 文件名，不带后缀
     * @return 类名及对应的字节码。文件不存在则返回null
     * @throws FileNotFoundException 文件不存在
     */
    public static Map<String, byte[]> read(String dir, String fileName) throws FileNotFoundException {
        String jarFileName = getJARFileName(dir, fileName);
        File jarFile = new File(jarFileName);
        if (!jarFile.exists()) {
            throw new FileNotFoundException(jarFileName);
        }
        try (JarInputStream jarInputStream = new JarInputStream(Files.newInputStream(Paths.get(jarFileName)))) {
            Map<String, byte[]> classMap = new HashMap<>();
            JarEntry jarEntry;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(CLASS_FILE_EXTENSION)) {
                    String className = jarEntry.getName()
                            .substring(0, jarEntry.getName().length() - CLASS_FILE_EXTENSION.length())
                            .replace(JAR_FILE_SEPARATOR, '.');
                    byte[] classBytes = IOUtils.toByteArray(jarInputStream);
                    classMap.put(className, classBytes);
                }
            }
            return classMap;
        } catch (IOException e) {
            throw new JitIOException(e.getMessage(), e);
        }
    }

    /**
     * 根据全限定类名获取其在JAR文件中的路径
     */
    private static String getJARFileEntryName(String className) {
        return className.replace('.', JAR_FILE_SEPARATOR) + CLASS_FILE_EXTENSION;
    }

    /**
     * @param dir      文件目录
     * @param fileName 文件名，不带后缀
     * @return 完整文件路径，文件名带后缀
     */
    private static String getJARFileName(String dir, String fileName) {
        return DirectoryManager.joinFilePath(dir, fileName + JAR_FILE_EXTENSION);
    }
}
